import {
	Card,
	Breadcrumb,
	Form,
	Button,
	Radio,
	Input,
	Upload,
	Space,
	Select,
	message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
// 富文本组件
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { http } from '@/utils'
import { useStore } from '@/store';
import './index.scss';
import { useEffect, useRef, useState } from 'react';
const { Option } = Select;
// 存储上传图片数组
const Publish = () => {
	/*
	 * @desc:获取路由id
	 * @param:no
	 * @date:
	 * @author:szd
	 */
	const [params] = useSearchParams()
	const routerId = params.get('id') || ''
	/*
	 * @desc: 获取频道列表
	 * @param: no
	 * @date:
	 * @author:szd
	 */
	const { ChannelStore } = useStore()
	useEffect(() => {
		ChannelStore.getChannelList()
	}, [ChannelStore])

	/*
	 * @desc: 点击上传头像,存储头像信息
	 * @param: no
	 * @date:
	 * @author:szd
	 */
	const [fileList, setFileList] = useState();
	const imageList = useRef([])
	const onUploadChange = imageInfo => {
		const fileList = imageInfo.fileList.map(file => {
			// if have response data  Map it
			if (file.response) {
				return {
					url: file.response.data.url,
				};
			}
			return file;
		});
		setFileList(fileList);
		imageList.current = fileList
	}
	/*
	 * @desc: 首次映射编辑接口中的数据
	 * @param: RouterId
	 * @date:
	 * @author:szd
	 */
	const [form] = Form.useForm();
	useEffect(() => {
		async function getEditPublish() {
			const res = await http.get(`/mp/articles/${routerId}`)
			const data = res.data;
			// 映射input
			form.setFieldsValue({ ...data, type: data.cover.type })
			// 回显已上传头像
			const formImage = data.cover.images.map(url => ({ url }));
			/* 收集image数据 */
			setFileList(formImage)
			// 动态存储image
			imageList.current = formImage
			// 回显按钮状态
			setMaxImageCount(data.cover.type)
		}
		if (routerId) getEditPublish()
	}, [routerId])

	/*
	 * @desc: 点击单选框,控制上传数量
	 * @param: no
	 * @date: 2023年6月9日14:18:25
	 * @author:szd
	 */
	const [maxImageCount, setMaxImageCount] = useState(1)
	// control upload images count
	const changeImageCount = (e) => {
		console.log(e.target.value)
		const count = e.target.value
		setMaxImageCount(count)
		if (count === 1) {
			const firstImg = imageList.current[0]
			setFileList(!firstImg ? [] : [firstImg])
		}
		if (count == 3) {
			setFileList(imageList.current)
		}
	}

	/*
	 * @desc:点击按钮后,更新/新增文章
	 * @param: id, data
	 * @date:2023年6月9日14:23:04
	 * @author:szd
	 */
	const navigate = useNavigate()
	const onFinish = async (value) => {
		console.log(value)
		const { channel_id, content, title, type } = value
		const params = {
			channel_id,
			content,
			title,
			type: 1 < type ? 3 : type,
			cover: {
				type: 1 < type ? 3 : type,
				images: fileList.map(item => item.url)
			}
		}
		if (routerId) {
			await http.put(`/mp/articles/${routerId}?draft=false`, params)
		} else {
			await http.post('/mp/articles?draft=false', params)
		}
		message.success(`${routerId ? '更新成功' : '添加成功'}`)
		setTimeout(() => {
			navigate('/article')
		}, 500);
	}
	return (
		<div className="publish">
			<Card
				title={
					<Breadcrumb separator=">">
						<Breadcrumb.Item>
							<Link to="/home">首页</Link>
						</Breadcrumb.Item>
						<Breadcrumb.Item>{routerId ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
					</Breadcrumb>
				}
			>
				<Form
					form={form}
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 16 }}
					initialValues={{ type: 1 }}
					onFinish={onFinish}
				>
					<Form.Item
						label="标题"
						name="title"
						rules={[{ required: true, message: '请输入文章标题' }]}
					>
						<Input placeholder="请输入文章标题" style={{ width: 400 }} />
					</Form.Item>
					<Form.Item
						label="频道"
						name="channel_id"
						rules={[{ required: true, message: '请选择文章频道' }]}
					>
						<Select placeholder="请选择文章频道" style={{ width: 400 }}>
							{ChannelStore.channelList.map(item => (
								<Option key={item.id} value={item.id}>
									{item.name}
								</Option>
							))}
						</Select>
					</Form.Item>

					<Form.Item label="封面">
						<Form.Item name="type">
							<Radio.Group onChange={changeImageCount}>
								<Radio value={1}>单图</Radio>
								{
									maxImageCount === 2 ? <Radio value={2}>三图</Radio> : <Radio value={3}>三图</Radio>
								}
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						{
							maxImageCount > 0 && (
								<Upload
									name="image"
									listType="picture-card"
									className="avatar-uploader"
									showUploadList
									multiple={maxImageCount > 1}
									maxCount={maxImageCount}
									action="http://geek.itheima.net/v1_0/upload"
									fileList={fileList}
									onChange={onUploadChange}
								>
									<div style={{ marginTop: 8 }}>
										<PlusOutlined />
									</div>
								</Upload>
							)
						}
					</Form.Item>
					<Form.Item
						label="内容"
						name="content"
						rules={[{ required: true, message: '请输入文章内容' }]}
					>
						<ReactQuill
							className="publish-quill"
							theme="snow"
							placeholder="请输入文章内容"
						/>
					</Form.Item>

					<Form.Item wrapperCol={{ offset: 4 }}>
						<Space>
							<Button size="large" type="primary" htmlType="submit">
								{routerId ? '编辑' : '发布'}文章
							</Button>
						</Space>
					</Form.Item>
				</Form>
			</Card>
		</div>
	);
};

export default Publish;
